#include "Playing.h"
#include "m_camera.h"
#include "m_shader.h"
#include "Shape.h"
#include "brick.h"
#include "brickManager.h"
#include "bullet.h"
#include "game_state.h"
#include <set>
using namespace std;

float bullet_shoot_cd;
bool shoot_state;
struct Playing::Items
{
    BrickManager *brickManager;
    Shader shader;
};

Playing::Playing(GLFWwindow *window) : IScene(window) { items = new Items; }

void Playing::init()
{
    mouse.firstMouse = true;
    mouse.lastX = WINDOW_WIDTH / 2.0;
    mouse.lastY = WINDOW_HEIGHT / 2.0;
    Camera &camera = Camera::getinstance(WINDOW_WIDTH, WINDOW_HEIGHT);
    items->shader.setShader("..\\assets\\shaders\\shape_shader\\vertex.glsl", "..\\assets\\shaders\\shape_shader\\fragment.glsl");
    bullet_shoot_cd = 0;
    shoot_state = true;
    items->brickManager = new BrickManager;
    GameState::init();
}

void Playing::draw()
{
    if (!GameState::lost)
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    else
        glClearColor(0.8f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawObjects(items->shader);
}
void Playing::update(float dt)
{
    if (!GameState::lost)
    {
        updateObjects(dt);
        if (bullet_shoot_cd > 0)
            bullet_shoot_cd -= dt, shoot_state = false;
        else if (!shoot_state)
            shoot_state = true;
    }
}
void Playing::deinit()
{
    deinitObjects();
}

void Playing::restart()
{
    deinit();
    mouse.firstMouse = true;
    mouse.lastX = WINDOW_WIDTH / 2.0;
    mouse.lastY = WINDOW_HEIGHT / 2.0;
    bullet_shoot_cd = 0;
    shoot_state = true;
    items->brickManager = new BrickManager;
    GameState::init();
}

void Playing::cursor_pos_callback(double xpos, double ypos)
{
    if (mouse.firstMouse)
        mouse.lastX = xpos, mouse.lastY = ypos, mouse.firstMouse = false;
    float xoffset = xpos - mouse.lastX;
    float yoffset = mouse.lastY - ypos;
    mouse.lastX = xpos, mouse.lastY = ypos;
    float sensitivity = 0.1;
    Camera &camera = Camera::getinstance();
    camera.mouseMove(sensitivity, xoffset);
}

void Playing::mouse_button_callback(int button, int action, int mods)
{
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
        if (shoot_state)
        {
            Bullet *bullet = new Bullet();
            shoot_state = false;
            bullet_shoot_cd = 1.0 / 3;
        }
}
void Playing::key_callback(int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_R && action == GLFW_PRESS)
    {
        restart();
    }
}
